/*
 * @Author: 
 * @Date: 2022-02-15 14:36:06
 * @LastEditors: lqj
 * @LastEditTime: 2022-02-15 14:50:01
 * @Description: 通用的事件侦听器函数
 */

export const myEvent = {
  // 页面加载完成后
  readEvent: function(fn: any){
    "use strict"
    if(fn === null || fn === undefined){
      fn = document
    }
    let oldOnload: any = window.onload;
    if(typeof window.onload !== "function"){
      window.onload = fn
    } else {
      window.onload = function(){
        oldOnload()
        fn()
      }
    }
  },
  // 页面元素事件绑定
  addEvent: function(element:any,type:any,handle:Function){
    if(element.addEventListener){ // w3c
      // 参数分别表示事件类型、需要执行的函数、是否捕捉
      element.addEventListener(type,handle,false)
    } else if(element.attachEvent){
      element.attachEvent("on"+type,function(){
        handle.call(element)
      })
    } else {
      element["on"+type] = handle
    }
  },
  removeEvent: function(element:any,type:any,handle:Function){
    if(element.removeEventListener){
      element.removeEventListener(type,handle,false)
    } else if (element.detachEvent){
      element.detachEvent("on"+type,handle)
    } else {
      element["on"+type] = null
    }
  },
  stopPropagation: function(ev:any){
    if(ev.stopPropagation){
      ev.stopPropagation()
    } else {
      ev.cancelBubble = true
    }
  },
  preventDefault: function(ev:any){
    if(ev.preventDefault){
      ev.preventDefault()
    } else {
      ev.returnValue = false
    }
  },
  // 获取事件目标
  getTarget: function(event:any){
    return event.target || event.srcElement;
  },
  // 获取event对象的引用，取到事件的所有信息
  getEvent: function(e:any){
    let ev = e || window.event;
    if(!ev){
      let c = this.getEvent.caller
      while(c){
        ev = c.arguments[0]
        if(ev && Event === ev.constructor){
          break;
        }
        c = c.caller
      }
    }
    return ev
  }
}